﻿using UnityEngine;
using System.Collections;
using PlayerIOClient;

public class GameClient : MonoBehaviour {
	public static GameClient instance;
	
	void Awake() {
		//make sure there is only one client at the same time
		if (instance==null) {
			Debug.Log ("GameClient.Awake");
			instance=this;
			DontDestroyOnLoad(this);
		}
		else
			enabled = false;
	}

	// Connection
	public bool isConnected = false;
	public PlayerIOClient.Client client;
	public DatabaseObject playerObject;
	
	public delegate void ObjectLoaded(DatabaseObject playerObject);
	public event ObjectLoaded PlayerObjectLoaded; //database events
	
	void Start () {
		string userid = SystemInfo.deviceName;
		#if UNITY_EDITOR
		userid += "_editor";
		#endif
		
		PlayerIOClient.PlayerIO.Connect(
			"hexagon-vplkybteeynoinxqznipa",// Game id (Get your own at playerio.com. 1: Create user, 2:Goto admin pannel, 3:Create game, 4: Copy game id inside the "")
			"public",						// The id of the connection, as given in the settings section of the admin panel. By default, a connection with id='public' is created on all games.
			userid,							// The id of the user connecting. This can be any string you like. For instance, it might be "fb10239" if you´re building a Facebook app and the user connecting has id 10239
			null,							// If the connection identified by the connection id only accepts authenticated requests, the auth value generated based on UserId is added here
			null,
			null,
			delegate(Client client)
			{
				Debug.Log("GameClient.Start : Successfully connected to PlayerIO");
				this.client = client;
				isConnected = true;
				
				// Get player data
				client.BigDB.LoadMyPlayerObject(
					delegate(DatabaseObject playerObject) {
						Debug.Log("GameClient : BigDB.LoadMyPlayerObject result=" + playerObject);
						// trigger event
						this.playerObject = playerObject;
						if (PlayerObjectLoaded != null) {
							PlayerObjectLoaded(playerObject);
						}
					},
					delegate(PlayerIOError error) {
						Debug.Log("GameClient : BigDB.LoadMyPlayerObject error=" + error.Message);
						this.playerObject = null;
						isConnected = false;
					}
				);
			}
		);
	}
	
	// Update is called once per frame
	void Update () {
		//TODO Multiplayer: handle messages
	}
	
	public void SavePlayerObject() {
		if (playerObject != null) {
			playerObject.Save();
		}
	}
}
